package com.android.lovely.ui.dialog

import android.os.Build
import android.util.Log
import android.widget.NumberPicker
import androidx.fragment.app.activityViewModels
import com.android.lovely.databinding.DialogTransTimeBinding
import com.android.lovely.framework.BaseDialogFragment
import com.android.lovely.ui.viewmodel.TransViewModel
import com.kotlin.extensions.view.ViewExt.clickable

/**
 *
 * @author why
 * @date 2025/3/13 18:55
 */
class TransTimeDialog : BaseDialogFragment<DialogTransTimeBinding>() {
    val viewModel by activityViewModels<TransViewModel>()
    private var year = "2025"

    private var month = "0"


    override fun initializeViews() {
        year = viewModel.year
        month = viewModel.month

        binding.mainWheelRight.apply {
            // 配置数值范围
            minValue = 1
            maxValue = 12
            value = month.toInt() // 默认值
            hideNumberPickerDivider()
            scrollBarSize = 0
            setFormatter { value ->
                value.toString().padStart(2, '0')
            }
            // 监听数值变化
            setOnValueChangedListener { _, oldVal, newVal ->
                Log.d("Picker", "值变化：$oldVal -> $newVal")
                month = newVal.toString()
            }
        }

        binding.mainWheelLeft.apply {
            // 配置数值范围
            minValue = 2025
            maxValue = 2100
            value = year.toInt() // 默认值
            hideNumberPickerDivider()
            scrollBarSize = 0

// 监听数值变化
            setOnValueChangedListener { _, oldVal, newVal ->
                Log.d("Picker", "值变化：$oldVal -> $newVal")
                year = newVal.toString()
            }
        }

        binding.ivClose.clickable {
            dismissAllowingStateLoss()
        }
        binding.confirmBtn.clickable {
            viewModel.year = year
            viewModel.month = month
            viewModel.updateType()
            dismissAllowingStateLoss()
        }
    }

    override fun isBottom(): Boolean {
        return true
    }

}

// 自定义设置文本颜色的方法（如果 NumberPicker 支持）

fun NumberPicker.hideNumberPickerDivider() {
    // API Level 29 及以上（Android 10+）
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        // 官方 API 设置透明分割线
        this.selectionDividerHeight = 0
    }
    // API Level 28 及以下（Android 9-）
    else {
        try {
            // 通过反射移除分割线
            val dividerField = NumberPicker::class.java.getDeclaredField("mSelectionDivider")
            dividerField.isAccessible = true
            dividerField.set(this, null)
        } catch (e: Exception) {
            // 备用方案：设置分割线高度为 0
//            this.selectionDividerHeight = 0
        }
    }
}

